package core.cards.election.gui;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import core.cards.election.model.VotingCardOption;
import core.gui.ValidationWizardPage;

public class WzdPgAddEditVotingCardOption extends ValidationWizardPage {

	private boolean addVotingCardOption;
	private VotingCardOption votingCardOption;

	private Text txtName;

	/**
	 * Create the wizard.
	 * 
	 * @param votingCard
	 * @param addVotingCard
	 */
	public WzdPgAddEditVotingCardOption(boolean addVotingCardOption, VotingCardOption votingCardOption) {
		super("WzdPgAddEditVotingCardOption");
		if (addVotingCardOption) {
			setTitle("Add Voting Card Option");
			setDescription("Add new Voting Card Option to the Voting Card.");
		} else {
			setTitle("Edit Voting Card Option");
			setDescription("Edit an existing Voting Card Option of the Voting Card.");
		}

		this.addVotingCardOption = addVotingCardOption;
		this.votingCardOption = votingCardOption;
	}

	/**
	 * Create contents of the wizard.
	 * 
	 * @param parent
	 */
	public void createControl(Composite parent) {
		Composite container = new Composite(parent, SWT.NULL);

		setControl(container);

		container.setLayout(new GridLayout(2, false));

		new Label(container, SWT.NONE).setText("Name:");

		txtName = new Text(container, SWT.BORDER | SWT.SINGLE);
		txtName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

		initValues();
		setValidationListeners();
	}

	private void initValues() {
		if (addVotingCardOption) {
			setPageComplete(false);
		} else {
			txtName.setText(votingCardOption.getName());
		}
	}

	private void setValidationListeners() {
		txtName.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent arg0) {
				validate();
			}
		});
	}

	@Override
	protected void validate() {
		String name = txtName.getText().trim();

		// error
		if (name.length() == 0) {
			setErrorState("Name cannot be empty.");
			return;
		}

		// ok
		clearErrorState();
	}

	@Override
	protected void update() {
		votingCardOption.setName(txtName.getText().trim());
	}
}
